package cn.ondraw.ragflow.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.ondraw.common.core.domain.R;
import cn.ondraw.ragflow.pojo.request.ChatRequest;
import cn.ondraw.ragflow.service.OpenAICompatibleService;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/v1/chats")
public class OpenAICompatibleController {

    private final OpenAICompatibleService openAICompatibleService;

    /**
     * 创建聊天完成
     *
     * @param chatId  聊天 ID
     * @param request 聊天请求对象
     * @return 非流形式的聊天响应对象
     */
    @PostMapping("/chats_openai/{chatId}/chat/completions")
    public R<Object> createChatCompletion(@RequestParam String chatId, @RequestBody ChatRequest request) {
        try {
            return R.ok(openAICompatibleService.createChatCompletion(chatId, request));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 创建代理完成
     *
     * @param agentId 代理 ID
     * @param request 聊天请求对象
     * @return 非流形式的聊天响应对象
     */
    @PostMapping("/agents_openai/{agentId}/chat/completions")
    public R<Object> createAgentCompletion(@RequestParam String agentId, @RequestBody ChatRequest request) {
        try {
            return R.ok(openAICompatibleService.createAgentCompletion(agentId, request));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 创建聊天完成（流形式）
     *
     * @param chatId  聊天 ID
     * @param request 聊天请求对象
     * @return 流形式的聊天响应对象
     */
    @PostMapping("/chats_openai/{chatId}/chat/completions/stream")
    public R<Object> createChatCompletionStream(@RequestParam String chatId, @RequestBody ChatRequest request) {
        try {
            return R.ok(openAICompatibleService.createChatCompletionStream(chatId, request));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 创建代理完成（流形式）
     *
     * @param agentId 代理 ID
     * @param request 聊天请求对象
     * @return 流形式的聊天响应对象
     */
    @PostMapping("/agents_openai/{agentId}/chat/completions/stream")
    public R<Object> createAgentCompletionStream(@RequestParam String agentId, @RequestBody ChatRequest request) {
        try {
            return R.ok(openAICompatibleService.createAgentCompletionStream(agentId, request));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}
